<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form :model="listQuery" :inline="true" ref="filterForm" style="display: inline-block">
                <el-form-item prop="appId" class="filter-item">
                    <el-select v-model="listQuery.appId" placeholder="应用" clearable style="width: 250px">
                        <el-option
                                v-for="item in appListOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="name" class="filter-item">
                    <el-input v-model="listQuery.name" placeholder="角色名称" style="width: 200px;"></el-input>
                </el-form-item>
                <el-form-item prop="orderBy" class="filter-item">
                    <el-select v-model="listQuery.orderBy" placeholder="排序" style="width: 150px">
                        <el-option
                                v-for="item in sortOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
                <el-button class="filter-item" type="primary" icon="mars-reset" @click="handleResetFilter">重置</el-button>

                <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="plus" @click="handleCreate()">
                    添加
                </el-button>
            </el-form>
        </div>

        <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%">

            <el-table-column label="ID" width="65" align="center">
                <template slot-scope="scope"> {{scope.row.id}} </template>
            </el-table-column>

            <el-table-column label="角色名称" width="300px" align="center">
                <template slot-scope="scope"> {{scope.row.name}} </template>
            </el-table-column>

            <el-table-column label="唯一标识" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.code}} </template>
            </el-table-column>

            <el-table-column label="备注" min-width="300px" align="center">
                <template slot-scope="scope"> {{scope.row.remarks}} </template>
            </el-table-column>

            <el-table-column label="创建时间" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
            </el-table-column>

            <el-table-column label="操作" width="380px" align="center">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" icon="mars-permission-setting" @click="handleApplyPermission(scope.row)">分配权限</el-button>
                    <el-button size="small" type="primary" icon="mars-m" @click="handleUserList(scope.row)">用户列表</el-button>
                    <el-button size="small" type="primary" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>

                    <el-button size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="listQuery.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="listQuery.rows"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" size="tiny" @close="handleCloseDialog">
            <el-form :model="form" :rules="rules" ref="form" labelPosition="right" labelWidth="80px" style="width: 400px">
                <el-form-item label="所属应用">
                    <el-select v-model="form.appId" placeholder="应用">
                        <el-option
                                v-for="item in appListOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>

                <el-form-item label="唯一表示" prop="code">
                    <el-input v-model="form.code"></el-input>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入内容"
                            v-model="form.remarks">
                    </el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="create">确 定</el-button>
                <el-button v-else="" type="primary" @click="update">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import fetch from '@/utils/fetch'
    import { created, deleted, updated, fetchObject, fetchList } from '@/api/upms/role'
    import { fetchList as fetchAppList } from '@/api/upms/app'

    const sortOptions = [{label: '按ID升序', key: 'id asc'}, {label: '按ID降序', key: 'id desc'}]

    export default {
        name: 'user',
        data() {
            return {
                list: null,
                total: null,
                listLoading: true,
                appListOptions: [],
                listQuery: {
                    page: 1,
                    rows: 10,
                    name: undefined,
                    code: undefined,
                    appId: undefined,
                    orderBy: 'id asc'
                },
                sortOptions,
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '创建'
                },
                form: {
                    appId: undefined,
                    name: '',
                    code: '',
                    remarks: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ],
                    code: [
                        { required: true, message: '请输入唯一表示', trigger: 'blur' }
                    ]
                }

            }
        },
        created() {
            this.getList()
            this.getAppList()
        },
        filters: {
        },
        methods: {
            getList() {
                this.listLoading = true
                fetchList(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                }).catch((error)=>{
                    console.log(error)
                    this.listLoading = false
                })
            },
            getAppList() {
                fetchAppList().then(response => {
                    for(let item of response.data.list) {
                        this.appListOptions.push({'label': item.name, 'key': item.id})
                    }
                }).catch((error)=>{
                    console.log(error)
                })
            },
            handleSizeChange(val) {
                this.listQuery.rows = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleCloseDialog() {
                this.resetForm()
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleResetFilter() {
                this.$refs.filterForm.resetFields()
                this.getList()
            },
            handleCreate() {
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
            },
            handleApplyPermission(row) {
                this.$router.push({path: `/upms/role/apply-permission/${row.id}`})
            },
            handleUpdate(row) {
                this.dialogStatus = 'update'
                fetchObject(row.id).then(response => {
                    this.dialogFormVisible = true
                    this.form = Object.assign({}, response.data)
                })
            },
            handleDelete(row) {
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(row.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getList()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            create() {
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        created(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getList()
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })

            },
            update() {
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getList()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })
            },
            handleUserList(row) {
                this.$router.push({path: `/upms/role/userlist/${row.id}`})
            },
            resetForm() {
                this.$refs['form'].resetFields()
                this.form = {
                    appId: '',
                    name: '',
                    code: '',
                    remarks: ''
                }
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>

</style>